import * as TE from 'TEngine';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/Addons.js';
import { emissive } from 'three/tsl';
import { Pane } from 'tweakpane';
const TS = new TE.TEngine();
TS.camera.position.set(10, 10, 10);
TS.camera.lookAt(0, 0, 0);

const axes = new THREE.AxesHelper(5);
TS.scene.add(axes);

function removeText(originalText, textToRemove) {
  if (!originalText || !textToRemove) return originalText;

  const regex = new RegExp(textToRemove, 'g'); // 全局匹配要删除的文本
  return originalText.replace(regex, '');
}
function textureToBase64(texture) {
  const image = texture.image;
  let canvas;
  // 如果 image 本身就是一个 canvas，可以直接使用
  if (image instanceof HTMLCanvasElement) {
    canvas = image;
  } else {
    canvas = document.createElement('canvas');
    canvas.width = image.width;
    canvas.height = image.height;
    const context = canvas.getContext('2d');
    context.drawImage(image, 0, 0);
  }
  // 默认输出 PNG 格式，可根据需要传入其它格式参数，如 "image/jpeg"
  return canvas.toDataURL();
}

function downloadJson(data, filename = 'data.json') {
  // 将对象转换为格式化后的 JSON 字符串
  const jsonStr = JSON.stringify(data, null, 2);
  // 创建 Blob 对象，指定 MIME 类型为 application/json
  const blob = new Blob([jsonStr], { type: 'application/json' });
  // 创建一个 URL 指向 Blob 对象
  const url = URL.createObjectURL(blob);

  // 创建一个隐藏的 a 标签，用于触发下载
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;

  // 将 a 标签添加到文档中，然后模拟点击
  document.body.appendChild(link);
  link.click();

  // 下载完成后移除 a 标签并释放 Blob URL
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

const mateiralArray = [];
//加载模型
const loader = new GLTFLoader();
loader.load('/public/models/scene.gltf', (model) => {
  console.log(model);

  model.scene.traverse((child) => {
    if (child.material) {
      const material = child.material;
      const objMat = {
        type: material.type,
        color: `#${material.color.getHexString()}`,
        roughness: material.roughness,
        metalness: material.metalness,
        name: material.name,
        chineseName: removeText(child.parent.name, 'glb'),
        transparent: material.transparent,
        opacity: material.opacity,
        emissive: `#${material.emissive.getHexString()}`,
      };
      for (let s in child.material) {
        if (child.material[s]?.isTexture) {
          objMat[s] = textureToBase64(child.material[s]);
        }
      }

      mateiralArray.push(objMat);
    }
  });
  console.log(mateiralArray, 'mateiralArray');

  TS.scene.add(model.scene);
});

const panel = new Pane();

panel.addButton({ label: '导出参数', title: '参数名称' }).on('click', () => {
  console.log(mateiralArray);
  // mateiralArray.forEach((item) => {
  //   downloadJson(item, `${item.name}.json`);
  // });
  downloadJson(mateiralArray, 'data.json');
});
